<template>
  <div class="sales-trend-chart">
    <div class="chart-header">
      <h3 class="chart-title">{{ title }}</h3>
      <div class="chart-actions">
        <div class="time-range-selector">
          <button 
            v-for="(range, index) in timeRanges" 
            :key="index"
            :class="{ active: selectedRange === range.value }"
            @click="changeTimeRange(range.value)"
          >
            {{ range.label }}
          </button>
        </div>
      </div>
    </div>
    
    <div class="chart-container" ref="chartContainer">
      <div v-if="loading" class="chart-loading">
        <div class="loading-spinner"></div>
        <span>加载中...</span>
      </div>
      <apexchart
        v-else
        type="line"
        height="350"
        :options="chartOptions"
        :series="series"
      ></apexchart>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, nextTick } from 'vue';
import { generateSalesTrendData } from '@/utils/agentMock';
import VueApexCharts from 'vue3-apexcharts';

interface Props {
  title?: string;
  height?: number;
  showSales?: boolean;
  showOrders?: boolean;
  showCommission?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  title: '销售趋势分析',
  height: 350,
  showSales: true,
  showOrders: true,
  showCommission: true
});

// 状态
const loading = ref(true);
const chartContainer = ref<HTMLElement | null>(null);
const timeRanges = [
  { label: '7天', value: 7 },
  { label: '30天', value: 30 },
  { label: '90天', value: 90 }
];
const selectedRange = ref(30);
const chartData = ref<any[]>([]);

// 获取数据
const fetchData = async () => {
  loading.value = true;
  try {
    // 使用模拟数据
    chartData.value = generateSalesTrendData(selectedRange.value);
    
    // 添加延迟让图表正确渲染
    await nextTick();
    setTimeout(() => {
      loading.value = false;
    }, 300);
  } catch (error) {
    console.error('获取销售趋势数据失败:', error);
    loading.value = false;
  }
};

// 日期格式化处理
const formatDate = (dateStr: string) => {
  const date = new Date(dateStr);
  return `${date.getMonth() + 1}月${date.getDate()}日`;
};

// 图表数据处理
const dates = computed(() => {
  return chartData.value.map(item => formatDate(item.date));
});

const salesData = computed(() => {
  return props.showSales ? chartData.value.map(item => item.sales) : [];
});

const ordersData = computed(() => {
  return props.showOrders ? chartData.value.map(item => item.orders) : [];
});

const commissionData = computed(() => {
  return props.showCommission ? chartData.value.map(item => item.commission) : [];
});

// 图表系列
const series = computed(() => {
  const result = [];
  
  if (props.showSales) {
    result.push({
      name: '销售额',
      data: salesData.value,
      type: 'line'
    });
  }
  
  if (props.showOrders) {
    result.push({
      name: '订单数',
      data: ordersData.value,
      type: 'line'
    });
  }
  
  if (props.showCommission) {
    result.push({
      name: '佣金',
      data: commissionData.value,
      type: 'line'
    });
  }
  
  return result;
});

// 图表配置
const chartOptions = computed(() => {
  return {
    chart: {
      height: props.height,
      type: 'line',
      stacked: false,
      fontFamily: 'DM Sans, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
      toolbar: {
        show: true,
        tools: {
          download: true,
          selection: true,
          zoom: true,
          zoomin: true,
          zoomout: true,
          pan: true,
          reset: true
        }
      },
      zoom: {
        enabled: true
      },
      animations: {
        enabled: true,
        easing: 'easeinout',
        speed: 800,
        animateGradually: {
          enabled: true,
          delay: 150
        },
        dynamicAnimation: {
          enabled: true,
          speed: 350
        }
      }
    },
    dataLabels: {
      enabled: false
    },
    stroke: {
      width: [3, 3, 3],
      curve: 'smooth',
      dashArray: [0, 0, 0]
    },
    colors: ['#3b82f6', '#64748b', '#10b981'],
    title: {
      text: undefined, // 使用组件内的标题
      align: 'left'
    },
    xaxis: {
      categories: dates.value,
      labels: {
        style: {
          colors: '#64748b',
          fontSize: '12px',
          fontFamily: 'DM Sans, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
          fontWeight: 400
        }
      },
      axisBorder: {
        show: false
      },
      axisTicks: {
        show: false
      }
    },
    yaxis: [
      {
        title: {
          text: '销售额',
          style: {
            color: '#3b82f6',
            fontSize: '13px',
            fontFamily: 'DM Sans, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
            fontWeight: 500
          }
        },
        labels: {
          formatter: function(val: number) {
            return '¥' + val.toLocaleString('zh-CN', { 
              minimumFractionDigits: 0,
              maximumFractionDigits: 0
            });
          },
          style: {
            colors: '#64748b',
            fontSize: '12px',
            fontFamily: 'DM Sans, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'
          }
        }
      },
      {
        title: {
          text: '订单数',
          style: {
            color: '#64748b',
            fontSize: '13px',
            fontFamily: 'DM Sans, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
            fontWeight: 500
          }
        },
        opposite: true,
        labels: {
          formatter: function(val: number) {
            return val.toFixed(0);
          },
          style: {
            colors: '#64748b',
            fontSize: '12px',
            fontFamily: 'DM Sans, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'
          }
        }
      },
      {
        title: {
          text: '佣金',
          style: {
            color: '#10b981',
            fontSize: '13px',
            fontFamily: 'DM Sans, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
            fontWeight: 500
          }
        },
        opposite: true,
        labels: {
          formatter: function(val: number) {
            return '¥' + val.toLocaleString('zh-CN', { 
              minimumFractionDigits: 0,
              maximumFractionDigits: 0
            });
          },
          style: {
            colors: '#64748b',
            fontSize: '12px',
            fontFamily: 'DM Sans, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'
          }
        },
        showAlways: false
      }
    ],
    tooltip: {
      shared: true,
      intersect: false,
      theme: 'light',
      style: {
        fontSize: '12px',
        fontFamily: 'DM Sans, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'
      },
      y: {
        formatter: function(value: number, { seriesIndex }: { seriesIndex: number }) {
          if (seriesIndex === 0 || seriesIndex === 2) {
            // 销售额和佣金使用货币格式
            return '¥' + value.toLocaleString('zh-CN', { 
              minimumFractionDigits: 2,
              maximumFractionDigits: 2
            });
          } else {
            // 订单数使用整数
            return value.toFixed(0);
          }
        }
      }
    },
    legend: {
      position: 'top',
      horizontalAlign: 'right',
      floating: false,
      offsetY: -5,
      markers: {
        width: 12,
        height: 12,
        radius: 6
      },
      itemMargin: {
        horizontal: 15
      },
      fontFamily: 'DM Sans, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
      fontSize: '13px'
    },
    grid: {
      borderColor: '#e2e8f0',
      strokeDashArray: 5,
      padding: {
        left: 0,
        right: 0
      }
    },
    responsive: [
      {
        breakpoint: 768,
        options: {
          legend: {
            position: 'bottom',
            horizontalAlign: 'center'
          }
        }
      }
    ]
  };
});

// 更改时间范围
const changeTimeRange = (days: number) => {
  selectedRange.value = days;
  fetchData();
};

// 监听属性变化
watch(
  () => [props.showSales, props.showOrders, props.showCommission],
  () => {
    // 属性变化时更新图表
    if (chartData.value.length > 0) {
      // 已有数据，不需要重新获取
    }
  }
);

// 初始化
onMounted(() => {
  fetchData();
  
  // 监听窗口大小变化，重绘图表
  window.addEventListener('resize', () => {
    if (!loading.value) {
      // 触发图表重绘
      window.dispatchEvent(new Event('resize'));
    }
  });
});
</script>

<style lang="scss" scoped>
.sales-trend-chart {
  background-color: #fff;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.03);
  padding: 24px;
  height: 100%;
  width: 100%;
  border: 1px solid rgba(226, 232, 240, 0.7);
  display: flex;
  flex-direction: column;
  
  .chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    flex-wrap: wrap;
    
    .chart-title {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: #1e293b;
      position: relative;
      padding-left: 16px;
      
      &:before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 6px;
        height: 20px;
        background: linear-gradient(to bottom, #3b82f6, #38bdf8);
        border-radius: 3px;
      }
    }
    
    .chart-actions {
      display: flex;
      align-items: center;
      
      .time-range-selector {
        display: flex;
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
        
        button {
          padding: 8px 14px;
          background: #f8fafc;
          border: 1px solid #e2e8f0;
          font-size: 14px;
          font-weight: 500;
          color: #64748b;
          cursor: pointer;
          transition: all 0.2s ease;
          
          &:not(:last-child) {
            border-right: none;
          }
          
          &:hover {
            background-color: #f1f5f9;
          }
          
          &.active {
            background: linear-gradient(90deg, #3b82f6, #38bdf8);
            color: #fff;
            border-color: #3b82f6;
            box-shadow: 0 2px 5px rgba(59, 130, 246, 0.2);
          }
        }
      }
    }
  }
  
  .chart-container {
    position: relative;
    flex: 1;
    min-height: 320px;
    width: 100%;
    overflow: hidden; /* 防止内容溢出 */
    
    .chart-loading {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      background-color: rgba(255, 255, 255, 0.8);
      z-index: 10;
      
      .loading-spinner {
        width: 40px;
        height: 40px;
        border: 3px solid #f1f5f9;
        border-top: 3px solid #3b82f6;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin-bottom: 10px;
      }
      
      span {
        color: #64748b;
        font-size: 14px;
      }
    }
    
    canvas {
      width: 100% !important;
      height: 100% !important;
      max-width: 100%;
    }
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

:deep(.apexcharts-menu) {
  background: #fff !important;
  border: 1px solid #e2e8f0 !important;
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1) !important;
}

:deep(.apexcharts-tooltip) {
  background: #fff !important;
  border: 1px solid #e2e8f0 !important;
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1) !important;
  border-radius: 8px !important;
}

@media (max-width: 768px) {
  .sales-trend-chart {
    padding: 18px;
    
    .chart-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 12px;
      
      .chart-title {
        margin-bottom: 0;
      }
      
      .chart-actions {
        width: 100%;
        
        .time-range-selector {
          width: 100%;
          
          button {
            flex: 1;
            text-align: center;
          }
        }
      }
    }
    
    .chart-container {
      min-height: 250px;
    }
  }
}

/* IE11 兼容性修复 */
@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {
  .sales-trend-chart {
    .chart-header {
      display: -ms-flexbox;
      -ms-flex-wrap: wrap;
      -ms-flex-pack: justify;
    }
    
    .chart-actions {
      display: -ms-flexbox;
      -ms-flex-align: center;
      
      .time-range-selector {
        display: -ms-flexbox;
        
        button {
          -ms-flex: 1 1 auto;
        }
      }
    }
    
    .chart-container {
      height: 350px;
    }
  }
  
  .chart-loading {
    display: -ms-flexbox;
    -ms-flex-direction: column;
    -ms-flex-align: center;
    -ms-flex-pack: center;
  }
}
</style> 